import sys
import os
from pathlib import Path
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QSettings,QUrl,Qt,QDir,QSize,pyqtSignal,pyqtSlot,pyqtProperty
from PyQt5.QtGui import QIcon
from PyQt5.QtQml import QQmlApplicationEngine,qmlRegisterType
from PyQt5.QtQuick import QQuickView
import Bridge
# from bpptablemodel import BTModel
import platform
import logging
from logging.handlers import RotatingFileHandler
import getpath
from Trans import Trans
import DeviceAddModel
from TaoFrameLessView import TaoFrameLessView
sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
sys.stderr = open(sys.stderr.fileno(), mode='w', encoding='utf8', buffering=1)
handlers = [RotatingFileHandler(filename="report.log", maxBytes=10 * 1024 * 1024, encoding='utf-8', backupCount=3),
            logging.StreamHandler(sys.stdout)]
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(name)s - %(levelname)s -%(funcName)s - %(message)s',
                    handlers=handlers)
logging.info('begin')

class AppInfo:
    def beforeUiReady(self,p):
        pass
    def afterUiReady(self):
        pass
    pass
class QuickTool:
    def setRootObjet(self,p):
        pass
    pass
# class TaoFrameLessView(QQuickView):
#     mousePressed=pyqtSignal()
#     def moveToScreenCenter(self):
#         pass
#     @pyqtSlot()
#     def setTitleItem(self):
#         pass
#     isMaxChanged=pyqtSignal()
#     @pyqtProperty(bool, notify=isMaxChanged)
#     def isMax(self):
#         return False

trans=None
appInfo=None
quickTool=None
view=None
def url_str(localpath):
    qurl=QUrl.fromLocalFile(localpath)
    url=str(qurl.url())+"/"
    logging.info(['url',url,type(url)])
    return url
def view_status(status):
    if (status == QQuickView.Status.Ready):
        trans.afterUiReady();
        appInfo.afterUiReady();
        quickTool.setRootObjet(view.rootObject());
def main():
    global trans,appInfo,quickTool,view
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling);
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps);
    QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough);
    QApplication.setOrganizationName("JaredTao");
    QApplication.setOrganizationDomain("https://jaredtao.github.io");
    QApplication.setApplicationName("TaoQuickShow");
    app=QApplication(sys.argv)
# #ifdef TAODEBUG
#     qSetMessagePattern("[%{time h:mm:ss.zzz} %{file} row(%{line}) %{function}] %{message}");
# #else
#     Logger::initLog();
# #endif
    appPath = QDir.cleanPath(app.applicationDirPath())
    logging.warning(["appPath" , appPath])

    taoQuickShowPath =getpath.getpath()+os.path.sep
    taoQuickShowPath=taoQuickShowPath.replace("\\","/")
    transDir         = taoQuickShowPath + "Trans"
    qmlPath      = taoQuickShowPath + "Qml"
    imgPath      = taoQuickShowPath + "Image"
    contentsPath = taoQuickShowPath + "Contents"
    print(qmlPath)
    trans=Trans()
    appInfo=AppInfo()
    quickTool=QuickTool()

    view=QQuickView() #TaoFrameLessView()
    view.setMinimumSize( QSize(800, 600 ))
    view.resize(1440, 960)
    # view.resize(800,600)
    trans.beforeUiReady(view.rootContext(), transDir);
    appInfo.beforeUiReady(view.rootContext());

    view.engine().addImportPath(qmlPath);

    TaoQuickImportPath= os.path.abspath(os.path.join(getpath.getpath(),"..","..","src"))
    print(TaoQuickImportPath)
    TaoQuickImportPath=TaoQuickImportPath.replace("\\","/")
    view.engine().addImportPath(TaoQuickImportPath);
    view.rootContext().setContextProperty("taoQuickImportPath", url_str(TaoQuickImportPath));
    view.rootContext().setContextProperty("isDebug", True);

    view.rootContext().setContextProperty("hasShape", True);

    view.rootContext().setContextProperty("comboBoxHasValueRole", True);

    view.rootContext().setContextProperty("scrollBarHasMinimumSize", True);

    view.rootContext().setContextProperty("appPath", url_str(appPath))
    view.rootContext().setContextProperty("qmlPath", url_str(qmlPath))
    view.rootContext().setContextProperty("imgPath", url_str(imgPath))
    view.rootContext().setContextProperty("contentsPath", url_str(contentsPath))
    view.rootContext().setContextProperty("view", view);
    view.rootContext().setContextProperty("quickTool", quickTool);

    model=DeviceAddModel.DeviceAddModel()
    logging.info(model)
    view.rootContext().setContextProperty("deviceAddModel",model );
    print(qmlPath)
    # lp=os.path.join(qmlPath,"main.qml")
    lp=os.path.join("Tables.qml")
    url=QUrl.fromLocalFile(lp)
    view.statusChanged.connect(view_status)
    view.engine().quit.connect(QApplication.quit)
    app.aboutToQuit.connect(lambda : view.setSource(QUrl("")))
    view.setSource(url);
    # view.moveToScreenCenter();
    view.show();
    return app.exec();


if __name__ == '__main__':
    main()
